package com.lyfx.ly.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lyfx.ly.controller.AttrAttrgroupController;
import com.lyfx.ly.dao.AttrAttrgroupDao;
import com.lyfx.ly.dao.AttrGroupDao;
import com.lyfx.ly.dao.ClassCategoryDao;
import com.lyfx.ly.entity.AttrAttrgroupEntity;
import com.lyfx.ly.entity.AttrGroupEntity;
import com.lyfx.ly.entity.ClassCategoryEntity;
import com.lyfx.ly.service.ClassCategoryService;
import com.lyfx.ly.vo.AttrGroupRelationVo;
import com.lyfx.ly.vo.AttrRespVo;
import com.lyfx.ly.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyfx.common.utils.PageUtils;
import com.lyfx.common.utils.Query;

import com.lyfx.ly.dao.AttrDao;
import com.lyfx.ly.entity.AttrEntity;
import com.lyfx.ly.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupDao relationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    ClassCategoryDao categoryDao;

    @Autowired
    ClassCategoryService classCategoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //spring工具类 ,
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //保存关联关系
        if(attr.getAttrGroupId()!=null){
            AttrAttrgroupEntity attrgroupEntity = new AttrAttrgroupEntity();
            attrgroupEntity.setAttrGroupId(attr.getAttrGroupId());
            attrgroupEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(attrgroupEntity);
        }
    }

    @Override
    public PageUtils queryAttrPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(catelogId != 0){
            wrapper.eq("category_id", catelogId);
        }
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            //attr_id  attr_name
            wrapper.and((obj)->{
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //1、设置分类和分组的名字
            AttrAttrgroupEntity attrId = relationDao.selectOne(new QueryWrapper<AttrAttrgroupEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (attrId != null && attrId.getAttrGroupId()!=null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            ClassCategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCategoryId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,attrRespVo);

        //设置分组信息
        AttrAttrgroupEntity attrgroupEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupEntity>().eq("attr_id", attrId));
        if(attrgroupEntity!=null){
            attrRespVo.setAttrGroupId(attrgroupEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupEntity.getAttrGroupId());
            if(attrGroupEntity!=null){
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        //设置分类信息
        Long categoryId = byId.getCategoryId();
        Long[] categoryPath = classCategoryService.findCategoryPath(categoryId);
        attrRespVo.setCategoryPath(categoryPath);
        ClassCategoryEntity category = classCategoryService.getById(categoryId);
        if(category!=null){
            attrRespVo.setCatelogName(category.getName());
        }
        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        AttrAttrgroupEntity attrgroupEntity = new AttrAttrgroupEntity();
        attrgroupEntity.setAttrGroupId(attr.getAttrGroupId());
        attrgroupEntity.setAttrId(attr.getAttrId());
        Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupEntity>().eq("attr_id", attr.getAttrId()));
        //根据数量判断是新增还是修改
        if(count>0){
            //修改分组关联
            relationDao.update(attrgroupEntity,new QueryWrapper<AttrAttrgroupEntity>().eq("attr_id", attr.getAttrId()));
        }else{
            //新增分组关联
            relationDao.insert(attrgroupEntity);
        }
    }

    /**
     * 根据分组id查找所有关联的基本属性
     * @param attrgroupId
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds == null || attrIds.size()==0){
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
        return attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupEntity attrgroupEntity = new AttrAttrgroupEntity();
            BeanUtils.copyProperties(item, attrgroupEntity);
            return attrgroupEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(collect);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long categoryId = attrGroupEntity.getCategoryId();
        //当前分组只能关联别的分组没有引用的属性
        // - 1找到当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("category_id", categoryId));
        // - 2这些分组关联的属性
        List<Long> collect = group.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
        List<AttrAttrgroupEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        // - 3、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("category_id", categoryId);
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }

        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> iPage = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(iPage);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrs(attrIds);
    }

}